/******************************************************************************
@file:  CabRequest.java
@author Ramesh Anandhan
DESCRIPTION
-----------------------------------------------------------------------------
Copyright (c) 2011, GEEKWAVE SOLUTIONS INC.

All rights reserved.
 ******************************************************************************/
package com.smartc.ui;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.smartc.connection.HttpConnection;
import com.smartc.connection.ParsedLoginData;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

public class CabRequest extends Activity implements OnClickListener {

	protected static final String TAG = "CabRequest";
	private final int DATE_DIALOG = 0x00;
	private final int TIME_DIALOG = 0x01;
	private final int DIALOG_STATUS = 0x02;
	private final int PROGRESS_DLG = 0x03;

	private EditText mEditCity = null;
	private EditText mEditName = null;
	private EditText mEditPPoint = null;
	private EditText mEditDPoint = null;
	private EditText mEditUser = null;
	private EditText mEditSId = null;
	private EditText mEditNumber = null;
	private Button mDate = null;
	private Button mTime = null;

	private Button mBtnSubmit = null;

	private HttpConnection mCityConnection;
	private ResponseHandler mResponse = new ResponseHandler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cab_request_1);

		mEditCity = (EditText) findViewById(R.id.cab_request_city);
		mEditName = (EditText) findViewById(R.id.cab_request_name);
		mEditPPoint = (EditText) findViewById(R.id.cab_request_ppoint);
		mEditDPoint = (EditText) findViewById(R.id.cab_request_dpoint);
		mEditUser = (EditText) findViewById(R.id.cab_request_userid);

		mEditSId = (EditText) findViewById(R.id.cab_request_superv_id);
		mEditNumber = (EditText) findViewById(R.id.cab_request_mnumber);

		mDate = (Button) findViewById(R.id.cab_request_date);
		mTime = (Button) findViewById(R.id.cab_request_time);
		mTime.setOnClickListener(this);
		mDate.setOnClickListener(this);

		mBtnSubmit = (Button) findViewById(R.id.cab_request_submit);
		mBtnSubmit.setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		if (AccountLogin.DEBUG)
			Log.i(TAG, "onClick");
		int id = arg0.getId();
		switch (id) {
		case R.id.cab_request_date:
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick cab_request_date:");
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(mDate.getWindowToken(), 0);
			showDialog(DATE_DIALOG);

			break;
		case R.id.cab_request_time:
			showDialog(TIME_DIALOG);
			break;
		case R.id.cab_request_submit:
			if(validateInput() == false)
				return;
			String city = mEditCity.getText().toString().trim();
			String name = mEditName.getText().toString().trim();
			String pickuppoint = mEditPPoint.getText().toString().trim();
			String droppoint = mEditDPoint.getText().toString().trim();
			String userid = mEditUser.getText().toString().trim();

			String supervisorId = mEditSId.getText().toString().trim();
			String number = mEditNumber.getText().toString().trim();
			String date = mDate.getText().toString().trim();
			String time = mTime.getText().toString().trim();

			String domain = getResources().getString(R.string.domain);
			String query = getResources().getString(R.string.url_cab_request);
			String url = domain + query;
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick url:" + url);

			mCityConnection = new HttpConnection();
			mCityConnection.setUrl(url);
			mCityConnection.AddHandler(mResponse);

			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick city:" + city);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick name:" + name);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick pickuppoint:" + pickuppoint);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick droppoint:" + droppoint);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick userid:" + userid);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick supervisorId:" + supervisorId);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick number:" + number);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick date:" + date);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "onClick time:" + time);

			// ParsedLoginData.mIdUser = "1";//TO_DO
			mCityConnection.AddParam("idUser", ParsedLoginData.mIdUser);
			mCityConnection.AddParam("nmCity", city);
			mCityConnection.AddParam("nmName", name);
			mCityConnection.AddParam("nmPickupPoint", pickuppoint);
			mCityConnection.AddParam("nmDroppingPoint", droppoint);
			mCityConnection.AddParam("nmUserId", userid);
			mCityConnection.AddParam("nmSupervicerId", supervisorId);
			mCityConnection.AddParam("nrMobileNumber", number);
			mCityConnection.AddParam("dtDate", date);
			mCityConnection.AddParam("tsTime", time);

			mCityConnection.Execute();
			showDialog(PROGRESS_DLG);
			break;
		}
	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		final Calendar cal = Calendar.getInstance();
		switch (id) {
		case DATE_DIALOG:
			int year = cal.get(Calendar.YEAR);
			int month = cal.get(Calendar.MONTH);
			int day = cal.get(Calendar.DAY_OF_MONTH);
			return new DatePickerDialog(this, dateListener, year, month, day);
		case TIME_DIALOG:
			int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
			int minute = cal.get(Calendar.MINUTE);
			return new TimePickerDialog(this, timeListener, hourOfDay, minute,
					true);
		case DIALOG_STATUS:
			return new AlertDialog.Builder(CabRequest.this).setMessage(
					mResponse.mMsg).setPositiveButton("OK", null).create();
		case PROGRESS_DLG:
			ProgressDialog mDialog = new ProgressDialog(this);
			mDialog.setMessage("Request In progress....");
			mDialog.setIndeterminate(true);
			mDialog.setCancelable(true);
			return mDialog;
		default:
			return super.onCreateDialog(id, args);
		}
	}

	private DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
		// @Override
		public void onDateSet(DatePicker view, int yr, int monthOfYear,
				int dayOfMonth) {
			String year = String.valueOf(yr);
			String month = String.valueOf(++monthOfYear);
			if (month.length() == 1)
				month = "0" + month;
			String day = String.valueOf(dayOfMonth);
			if (day.length() == 1)
				day = "0" + day;
			mDate.setText(year + ":" + month + ":" + day);
		}
	};

	private TimePickerDialog.OnTimeSetListener timeListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

			String hour = String.valueOf(hourOfDay);
			if (hour.length() == 1)
				hour = "0" + hour;
			String minutes = String.valueOf(minute);
			if (minutes.length() == 1)
				minutes = "0" + minutes;
			mTime.setText(hour + ":" + minutes);
		}

	};

	public class ResponseHandler extends DefaultHandler {

		//private boolean mMessages = false;
		private boolean mMessage = false;
		private boolean mStatus = false;

		public String mStatusMsg = null;
		public String mMsg = null;

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			if (this.mStatus) {
				mStatusMsg = new String(ch, start, length);
			} else if (this.mMessage) {
				mMsg = new String(ch, start, length);
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {

			if (localName.equals("Messages")) {
				//this.mMessages = false;
				Message myMessage = new Message();
				myMessage.obj = "STATUS";
				handler.sendMessage(myMessage);
			} else if (localName.equals("status")) {
				this.mStatus = false;
			} else if (localName.equals("message")) {
				this.mMessage = false;
			}
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			if (localName.equals("Messages")) {
				//this.mMessages = true;
			} else if (localName.equals("status")) {
				this.mStatus = true;
			} else if (localName.equals("message")) {
				this.mMessage = true;
			}
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage msg:" + (String) msg.obj);
			String loginmsg = (String) msg.obj;
			if (loginmsg.equals("STATUS")) {
				if (mResponse.mStatusMsg.equals("Success")) {
					removeDialog(PROGRESS_DLG);
					showDialog(DIALOG_STATUS);

					mEditCity.setText("");
					mEditName.setText("");
					mEditPPoint.setText("");
					mEditDPoint.setText("");
					mEditUser.setText("");
					mEditSId.setText("");
					mEditNumber.setText("");
					mDate.setText("");
					mTime.setText("");
				}
			}
		}
	};
	
	private boolean validateInput(){
		boolean valid = true;
		
		Date sysdate = Calendar.getInstance().getTime();
		if (AccountLogin.DEBUG)
			Log.i(TAG, "validateInput sysdate:" + sysdate);

		if(mEditCity.getText().toString().trim().length() <= 0 || 
				mEditName.getText().toString().trim().length() <=0   ||
				mEditPPoint.getText().toString().trim().length() <=0 ||
				mEditDPoint.getText().toString().trim().length() <=0 ||
				mEditUser.getText().toString().trim().length() <=0   ||
				mEditSId.getText().toString().trim().length() <=0	 ||
				mEditNumber.getText().toString().trim().length() <=0 ||
				mDate.getText().toString().trim().length() <=0		 ||
				mTime.getText().toString().trim().length() <=0
				){
			valid = false;
			Toast.makeText(this, "Enter All Input Fields", Toast.LENGTH_SHORT).show();
		}else{
			Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
			Matcher matcher = pattern.matcher(mEditSId.getText().toString().trim());
			if(!matcher.matches()){
				valid = false;
				Toast.makeText(this, "Enter valid Email Id", Toast.LENGTH_SHORT).show();
			}
			
			if (mEditNumber.getText().toString().trim().length()<10 || 
					mEditNumber.getText().toString().trim().length()>13
					/* || nmContact.matches(numStr)==false*/) {
				valid = false;
				Toast.makeText(this, "Enter valid Mobile Number", Toast.LENGTH_SHORT).show();
			}
			
			SimpleDateFormat format = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
			String strdate = mDate.getText().toString().trim();
			String time = mTime.getText().toString().trim();	
			strdate = strdate+" "+time+":00";
			Date date = null;
			try {
				date = (Date) format.parse(strdate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if (AccountLogin.DEBUG)
				Log.i(TAG, "validateInput date:" + date.toString());
			
			if(!date.after(sysdate)){
				valid = false;
				Toast.makeText(this, "Enter valid Date & Time", Toast.LENGTH_SHORT).show();
			}
		}
		return valid;
	}

}
